#include "Texture.h"
#include "Utils.h"
#include "Image.h"
#include "PngImage.h"
#include "Graphics.h"
#include "Rect.h"
#include <string.h>

Texture::Texture()
{
	texture = width = height = id = 0;
}

Texture::Texture(const char* fileName, int id)
{
	this->id = id;
	int len = strlen(fileName);

	Image* img = 0;
	if(fileName[len-1]=='g'&&fileName[len-2]=='n'
		&&fileName[len-3]=='p'&&fileName[len-4]=='.')		//PNG file type
	{
		img = new PngImage(fileName);
	}
	else
	{
		PRINT("File type does not support");
	}

	width = img->GetWidth();
	height = img->GetHeight();

	if(img != 0)
	{
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
			GL_UNSIGNED_BYTE, (GLvoid*) img->GetImageData());
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	}
}

void Texture::Render(int x, int y)
{
	Render(x, y, 0.0f);
}

void Texture::Render(int x, int y, float deep)
{
	Render(x, y, 1.0f, 1.0f, 0.0f, 1.0f , deep);
}

void Texture::Render(int x, int y, float xScale, float yScale, float angle, float alpha, float deep)
{
	Rect src;
	src.x = 0; src.y = 0; src.width = width; src.height = height;
	Render(x, y, &src, xScale, yScale, angle, alpha, deep);
}

void Texture::Render(int x, int y, Rect* src)
{
	Render(x, y, src, 1.0f);
}

void Texture::Render(int x, int y, Rect* src, float deep)
{
	Render(x, y, src, 1.0f, 1.0f, 0.0f, 1.0f, deep);
}

void Texture::Render(int x, int y, Rect* src, float alpha, float deep)
{
	Render(x, y, src, 1.0f, 1.0f, 0.0f, alpha, deep);
}

void Texture::Render(int x, int y, Rect* src, float xScale, float yScale, float angle, float alpha, float deep)
{
	Graphics* g = Graphics::GetInstance();
	Rect des;
	des.x = x; des.y = y; 
	des.width = src->width*xScale; des.height = src->height*yScale;
	g->RenderTexture(this, src, &des, angle, alpha, deep);
}

Texture::~Texture()
{
	PRINT("Destroy Texture %d\n",texture);
	glDeleteTextures(1, &texture);
}